from fastapi import APIRouter, Query
from typing import Union, Optional
from models.article_model import *
from utils.result import *
from datetime import datetime
from pydantic import BaseModel,validator,Field
import time

article = APIRouter()

@article.get('/index', summary=['文章分页列表'])
async def pageList(page: int = Query(1, ge=1), limit: int = Query(10, gt=1, le=30), categoryId:Optional[int]=None,status: Union[str, None] = None, title: Optional[str] = None):
    offset = (page - 1) * limit
    query = Article.all() #.prefetch_related( "article_relation").prefetch_related( "article_category_relation")
    if  status != None:
        query = query.filter(status = status)
    if categoryId:
        query = query.filter(category_id = categoryId)
    if title:
        query = query.filter(title__icontains = title)
    res = await query.limit(limit).offset(offset).order_by( '-id').all()
    print(res[0])
        #.values( 'id', 'title', 'status', 'created_at', 'updated_at', 'category_id')

    ids = []
    for  item in res:
        ids.append(int(item['category_id']))

    category = await ArticleCategory.all().filter(id__in = list(set(ids))).order_by('id')

    for item in res:
        for cate in category:
            if item['category_id'] == cate.id:
                item['category_name'] = cate.category_name
                break
            else:
                 item['category_name'] = ''

    count = await query.count()
    return success(data={
        'data':res,
        'total':count,
        'current_page':page,
        'last_page' : count//limit+1
    })

@article.get('/getInfo', summary=['文章详情'])
async def detail(id: Optional[int]):
    res = await Article.filter(id=id).first()
    return success(res)


class ArticleData(BaseModel):
    title: str = Field(max_length=155, description="标题")
    category_id: int = Field(description="分类ID")
    content: str = Field(description="内容")
    status: Optional[str] = 0
    updated_at: datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    @validator('title')
    def title_validator(cls, value):
        if (len(value) == 0 or len(value) > 155) :
            raise ValueError('标题155个字数以内')
        return value
    @validator('content')
    def content_validator(cls, value):
        assert len(value)  > 0, '内容不能为空'
        return value
@article.post('/addArticle',summary=['添加文章'])
async def addArticle(data : ArticleData):
    timestamp = int(datetime.now().timestamp())
    print(data,timestamp)
    entity =  Article(title=data.title,
                      category_id=data.category_id,
                      content=data.content,
                      status=data.status,
                      created_at= timestamp,
                      updated_at=data.updated_at)
    res = await entity.save()
    return success(res)

@article.post('/editArticle',summary=['修改文章'])
async def editArticle(id: Optional[int], data : ArticleData):
    res = await Article.filter(id=id).update(title=data.title,
                      category_id=data.category_id,
                      content=data.content,
                      status=data.status,
                      updated_at=data.updated_at)
    return success(res)

@article.post('/delArticle',summary=['删除文章'])
async def delArticle(id: Optional[int]):
    res = await Article.filter(id=id).delete()
    return success(res)

@article.get('/category', summary=['文章分类列表'])
async def category(page: int = Query(1, ge=1), limit: int = Query(10, gt=1, le=30), status: Union[str, None] = None, title: Optional[str] = None):
    offset = (page - 1) * limit
    query = ArticleCategory.all()
    if  status != None:
        query = query.filter(status = status)
    if title:
        query = query.filter(category_name__icontains = title)
    res = await query.limit(limit).offset(offset).order_by( '-id')
    count = await query.count()
    return success(data={
        'data':res,
        'total':count,
        'current_page':page,
        'last_page' : count//limit+1
    })

class Catgory(BaseModel):
    name: str = Field(max_length=55, description="分类名称")
    @validator('name')
    def name_validator(cls, value):
        assert len(value)  > 0 and len(value) <= 55, '分类名称55个字数以内'
        return value

@article.post('/addCategory', summary=['添加文章分类'])
async def addCategory(category : Catgory):
    res = await category.save(category)
    return success(res);